/**
 * 封装变化
 */
export { }
interface Window {
    hello: any
}
function Window(this:any) {
    this.a = 2
}
Window.prototype.hello = function () {
    console.log('hello');
}
//希望 封装变化，希望这个createInstance可以创建任何类型的实例 
let createInstance = function (Constructor: any) {
    let instance: any;
    return function AnyConstructor(this: any) {
        this.a = 1
        if (!instance) {
            console.log(this.a,'this1');// 1
            
            /**
             * 将Constructor的this指向AnyConstructor的this的空间，这时候在Constructor中设置的this的值就会修改到AnyConstructor的this
             * 所以this2 === 2
             * 
             */
            Constructor.apply(this, arguments);
            console.log(this.a,'this2');// 2
            
            //
            /**
             * 正常来说 this.__proto__=AnyConstructor.prototype
             * 但是我们return的this的__proto__要指向传入的构造函数
             * 所以用setPrototypeOf修改原型指向this.__proto__= Constructor.prototype
             */
            Object.setPrototypeOf(this, Constructor.prototype);
            // this是AnyConstructor的this，但是this对象里面的值是Constructor中的值
            instance = this;
        }
        return instance;
    }
}
let createWindow = createInstance(Window);
let w1 = new (createWindow as any)();
let w2 = new (createWindow as any)();
console.log(w1 === w2);

